package com.dq;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @ClassName SocketProcessor
 * @Description 处理socket的异步方法
 * @Author DuX1aoQiang
 * @Date 2023/5/28 16:55
 * @Version 1.0
 */
public class SocketProcessor implements Runnable {
    private Socket socket;

    public SocketProcessor(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        processSocket(socket);
    }

    private void processSocket(Socket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            inputStream.read(bytes);

            int pos = 0;
            int begin = 0, end = 0;
            for (; pos < bytes.length; pos++, end++) {
                if (bytes[pos] == ' ') break;
            }

            //获取请求协议类型
            StringBuilder method = new StringBuilder();
            for (; begin < end; begin++) {
                method.append((char) bytes[begin]);
            }

            //获取请求URL
            pos++;
            begin++;
            end++;
            for (; pos < bytes.length; pos++, end++) {
                if (bytes[pos] == ' ') break;
            }
            StringBuilder url = new StringBuilder();
            for (; begin < end; begin++) {
                url.append((char) bytes[begin]);
            }

            //获取协议版本
            pos++;
            begin++;
            end++;
            for (; pos < bytes.length; pos++, end++) {
                if (bytes[pos] == '\r') break;
            }
            StringBuilder protocol = new StringBuilder();
            for (; begin < end; begin++) {
                protocol.append((char) bytes[begin]);
            }

            System.out.println(method.toString() + ":" + url.toString() + ":" + protocol.toString());

            Request request = new Request(method, url, protocol, socket);
            Response response = new Response(request);
            ServletHandler servletHandler = new ServletHandler();
            servletHandler.service(request, response);

            response.complete();
        } catch (IOException | ServletException e) {
            throw new RuntimeException(e);
        }
    }
}
